package com.edu.hre.db.sql.pim;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.db.pojo.HreEmpReportto;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.pim.EmpSupervisorForm;
import com.edu.hre.struts.form.pim.EmpSupervisorListForm;

public class EmpSupervisorDAOService implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3394301416150421253L;
	public static final String BEAN_NAME = "empSupervisorDAOService";
	private BaseService baseService  = null;
	 
	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	} 

	public ArrayList<EmpSupervisorForm> getEmpSupervisorList(int limit, int offset, int empNumber){

		String sql = "SELECT rto.id AS col1," +
					" CONCAT (sup.emp_lastname, ' ', sup.emp_middle_name, ' ', sup.emp_firstname) AS col2," +
					" met.reporting_method_name AS col3 " +
					
					" FROM hre_emp_reportto AS rto" +
					" LEFT OUTER JOIN hre_employee AS sub ON rto.erep_sub_emp_number = sub.emp_number" +
					" LEFT OUTER JOIN hre_employee AS sup ON rto.erep_sup_emp_number = sup.emp_number" +
					" LEFT OUTER JOIN hre_emp_reporting_method AS met ON rto.erep_reporting_mode = met.reporting_method_id" +
					
					" WHERE sub.emp_number = ?" +
					" ORDER BY rto.date_created DESC";

		List <Object[]> listObject = baseService.listArrayObject(sql, limit, offset, empNumber);
		ArrayList<EmpSupervisorForm> listResult = new ArrayList<EmpSupervisorForm>();

		for(int i = 0; listObject != null && i < listObject.size(); i++){

			try {

				Object[] objs = listObject.get(i);
				EmpSupervisorForm supervisor = new EmpSupervisorForm();
				
				supervisor.setId(Integer.parseInt(CommonUtils.normalizeObjectToString(objs[1], "0")));
				supervisor.setEmpNumber(empNumber);
				supervisor.setSupervisorName(CommonUtils.normalizeObjectToString(objs[2], ""));
				supervisor.setReportingMethod(CommonUtils.normalizeObjectToString(objs[3], ""));
				
				listResult.add(supervisor);
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
		
		return listResult;
	}

	public int countEmpSupervisors(int empNumber){

		int count = baseService.countByColumns(new String[]{"erepSubEmpNumber"}, new int[]{Compare.EQUAL}, new Integer[]{empNumber}, "id", HreEmpReportto.class);
		return count < 0 ? 0 : count;
	}

	public void deleteSupervisors(EmpSupervisorListForm form){

		ArrayList<EmpSupervisorForm> info = (ArrayList<EmpSupervisorForm>) form.getAllSupervisors();

		for (int i = 0; i < info.size(); i++) {

			try {

				EmpSupervisorForm dep = info.get(i);
				if (dep.isSelected()) {
					baseService.deleteFirstPojo("id", Compare.EQUAL, dep.getId(), null, null, 0, HreEmpReportto.class);
				}
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
	}
}
